//
//  TheNewChoseViewController.m
//  NewMusic
//
//  Created by dllo on 15/11/16.
//  Copyright © 2015年 Going. All rights reserved.
//

#import "TheNewChoseViewController.h"
#import "TheNewChoseNextCollectionViewCell.h"
#import "CustomerNetworking.h"
#import "TheNewChoseModel.h"
#import "ClassifyButtonView.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "NavigationBarBackImageView.h"
#import "PlayerViewController.h"
#import "MusicType.h"
#import "SongsAuditionListModel.h"
#import "ListenDataSongsModel.h"
@interface TheNewChoseViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, UIScrollViewDelegate, TheNewChoseNextCollectionViewCellDelegate, classifyButtonViewDelegate>
@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, copy) NSString *nameString;
@property(nonatomic, retain) NSMutableArray *refsArray;
@property(nonatomic, retain) NSMutableArray *buttonArray;
//图片
@property(nonatomic, retain) UIImageView *picImageView;
//标题
@property(nonatomic, retain) UILabel *nameLabel;

@property(nonatomic, assign) CGFloat contenOffSizeY;
@property(nonatomic, retain) ClassifyButtonView *classifyButtonView;
@property(nonatomic, retain) UINavigationBar *bar;
@property(nonatomic, retain) UIImageView *backImage;
@property(nonatomic, retain) NavigationBarBackImageView *barBackImgeView;
@end

@implementation TheNewChoseViewController
- (void)dealloc {
    [_nameString release];
    [_nameLabel release];
    [_buttonArray release];
    [_refsArray release];
    [_picImageView release];
    [_bar release];
    [_backImage release];
    [_barBackImgeView release];
    [_classifyButtonView release];
    [_collectionView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.refsArray = [NSMutableArray array];
    self.buttonArray = [NSMutableArray array];
    //创建collectionView
    [self createCollectionView];
    //创建视图;
    [self createSubView];
    //自定义navigationBar
    [self createTabbar];
    //获取数据
    [self loadData];
}
#pragma mark 自定义navigationBar
- (void)createTabbar {
    self.bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 375, 64)];
    [self.view addSubview:self.bar];
    //navigationbar背景图片
    self.barBackImgeView = [[NavigationBarBackImageView alloc]initWithFrame:CGRectMake(0, 0, self.bar.frame.size.width, self.bar.frame.size.height)];
    _barBackImgeView.alpha = 0;
    [_bar addSubview:_barBackImgeView];
    [_barBackImgeView release];
    self.bar.tintColor = [UIColor whiteColor];
    [self.bar setBackgroundImage:[UIImage imageNamed:@"nav.jpg"] forBarMetrics:UIBarMetricsCompact];
    [[self findHairlineImageViewUnder:self.bar] setHidden:YES];
    UIBarButtonItem *itemBar = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(retutnAction:)];
    UINavigationItem *item = [[UINavigationItem alloc] init];
    [self.bar pushNavigationItem:item animated:YES];
    [item setLeftBarButtonItem:itemBar];
    [itemBar release];
    [_bar release];
}
- (void)retutnAction:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
#pragma mark 创建视图
- (void)createSubView {
    //图片
    self.picImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250)];
    //        _picImageView.backgroundColor = [UIColor redColor];
    _picImageView.userInteractionEnabled = YES;
    [self.view addSubview:_picImageView];
    [_picImageView release];
    //标题
    self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, self.picImageView.frame.size.height / 5 * 3, self.picImageView.frame.size.width / 2, 30)];
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:17];
    //    _nameLabel.backgroundColor = [UIColor purpleColor];
    [self.picImageView addSubview:_nameLabel];
    [_nameLabel release];
}
#pragma mark 获取数据
- (void)loadData {
    [CustomerNetworking customerConnectWithURL:@"http://api.songlist.ttpod.com/channels/xgjx?app=ttpod&v=v8.1.1.2015110616" andParameters:nil andBlock:^(id response) {
        self.nameLabel.text = [response valueForKey:@"name"];
        self.barBackImgeView.titleString = [response valueForKey:@"name"];
        NSArray *array = [response valueForKey:@"refs"];
        for (NSDictionary *dic in array) {
            TheNewChoseModel *model = [[TheNewChoseModel alloc]initWithDictionary:dic];
            [self.refsArray addObject:model];
            [self.buttonArray addObject:model.title];
            [model release];
        }
        if (_refsArray.count != 0) {
            [self.picImageView sd_setImageWithURL:[NSURL URLWithString:[_refsArray[0]  pic]]];
        }
        //分类视图
        self.classifyButtonView = [[ClassifyButtonView alloc]initWithFrame:CGRectMake(0,  self.picImageView.frame.size.height - 40, self.picImageView.frame.size.width, 40)];
        _classifyButtonView.delegate = self;
        [self.picImageView addSubview:_classifyButtonView];
        [_classifyButtonView release];
        
        if (_buttonArray.count != 0) {
            _classifyButtonView.titleArray = _buttonArray;
            _classifyButtonView.showLength = NO;
        }
        [_collectionView reloadData];
    }];
}
#pragma mark 创建collectionView
- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height ) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.contentOffset = CGPointMake(0, 250 - _picImageView.frame.size.height);
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    self.contenOffSizeY = _collectionView.contentOffset.x;
    //注册cell的重用标识
    [_collectionView registerClass:[TheNewChoseNextCollectionViewCell class] forCellWithReuseIdentifier:@"TheNewChoseNextCollectionViewCellIdentify"];
    [self.view addSubview:_collectionView];
    [flowLayout release];
    [_collectionView release];
}
#pragma mark cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TheNewChoseNextCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TheNewChoseNextCollectionViewCellIdentify" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.tableView.tag = 2700 + indexPath.row;
    cell.delegate = self;
    if (_refsArray.count != 0 ) {
        cell.songlistIdString = [[_refsArray objectAtIndex:indexPath.row] songlist_ID];
    }
    return cell;
}
#pragma mark cell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}
#pragma mark cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
}
#pragma mark cell的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
#pragma mark cell的最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
- (void)tableViewCellClickAction:(NSArray *)dataArray index:(NSInteger)index {
    PlayerViewController *player = [PlayerViewController sharePlayerViewController];
    NSMutableArray *arr = [NSMutableArray array];
    for (NSInteger i = 0; i < dataArray.count; i++)
    {
        ListenDataSongsModel *song = dataArray[i];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:song.albumName forKey:@"album"];// 专辑
        [dic setValue:song.name forKey:@"name"]; // 歌名
        NSMutableArray *array = [NSMutableArray array];
        for (SongsAuditionListModel *model in song.mvList) {
            MusicType *type = [[MusicType alloc]init];
            type.url = model.urlString;
            type.typeDescription = model.typeDescription;
            [array addObject:type];
        }
        [dic setValue:array forKey:@"music"]; // 歌曲,model用musicType
        [dic setValue:song.singerName forKey:@"songerName"];// 歌手名
        [dic setValue:song.albumId forKey:@"id"]; // id
        [arr addObject:dic];
    }
    player.musicArr = arr;
    [player MusicStart:index];
}

#pragma mark TheNewChoseNextCollectionViewCell代理方法
- (void)tableViewScrollFrame:(CGFloat)height tableViewContentOffY:(CGFloat)tableViewContentOffY top:(BOOL)top{
    NSLog(@"%f", tableViewContentOffY);
    if (top == YES) {
        self.picImageView.frame = CGRectMake(0, self.picImageView.frame.origin.y - height, self.view.frame.size.width, self.picImageView.frame.size.height);
        _classifyButtonView.backView.alpha = tableViewContentOffY / 146;
        if (_classifyButtonView.backView.alpha > 1) {
            _classifyButtonView.backView.alpha =  1;
        }else if (_classifyButtonView.backView.alpha < 0.7) {
            _classifyButtonView.backView.alpha =  0.7;
        }
        if (tableViewContentOffY > 146) {
            _classifyButtonView.frame = CGRectMake(0, 64, self.view.frame.size.width, 40);
            [self.view addSubview:_classifyButtonView];
        }
        _barBackImgeView.alpha = tableViewContentOffY / 146;
    }else {
        self.picImageView.frame = CGRectMake(0, self.picImageView.frame.origin.y - height, self.view.frame.size.width, self.picImageView.frame.size.height);
        _classifyButtonView.backView.alpha =  tableViewContentOffY / 146;
        if (_classifyButtonView.backView.alpha > 1) {
            _classifyButtonView.backView.alpha =  1;
        }else if (_classifyButtonView.backView.alpha < 0.7) {
            _classifyButtonView.backView.alpha =  0.7;
        }
        if (tableViewContentOffY < 146) {
            _classifyButtonView.frame = CGRectMake(0, _picImageView.frame.size.height - 40, self.view.frame.size.width, 40);
            [self.picImageView addSubview:_classifyButtonView];
        }
        _barBackImgeView.alpha = tableViewContentOffY / 146;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //    NSLog(@"%f", scrollView.contentOffset.x);
    NSInteger num = scrollView.contentOffset.x / self.view.frame.size.width;
    _classifyButtonView.buttonTag = 2500 + num;
    if (scrollView == self.collectionView && _contenOffSizeY != scrollView.contentOffset.x) {
        if (_refsArray.count != 0) {
            [self.picImageView sd_setImageWithURL:[NSURL URLWithString:[[_refsArray objectAtIndex:num] pic]]];
            CATransition *anim = [CATransition animation];
            anim.type = @"fade"; // 动画过渡类型
            anim.subtype = kCATransitionFromRight; // 动画过渡方向
            anim.duration = 1; // 动画持续1s
            // 代理，动画执行完毕后会调用delegate的animationDidStop:finished:
            anim.delegate = self;
            [self.picImageView.layer addAnimation:anim forKey:@"layer"];
        }
        self.contenOffSizeY = scrollView.contentOffset.x;
    }
    //    if ([scrollView isKindOfClass:[UICollectionView class]]) {
    //        NSLog(@"111111");
    //        self.picImageView.frame = CGRectMake(0, 0, self.view.frame.size.width, 250);
    //
    //    }
    //    for (int i = 0; i < 4; i++)
    //    {
    //
    //            NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
    //            TheNewChoseNextCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:index];
    //            [cell.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    //
    //    }
    
}
#pragma mark classifyButtonView的代理方法
- (void)buttonClickAction:(UIButton *)button {
    self.collectionView.contentOffset = CGPointMake(self.view.frame.size.width * (button.tag - 2500), -20);
    //    for (int i = 0; i < 4; i++)
    //    {
    //        NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
    //        TheNewChoseNextCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:index];
    //        [cell.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    //    }
    if (_refsArray.count != 0) {
        [self.picImageView sd_setImageWithURL:[NSURL URLWithString:[[_refsArray objectAtIndex:button.tag - 2500] pic]]];
        CATransition *anim = [CATransition animation];
        anim.type = @"fade"; // 动画过渡类型
        anim.subtype = kCATransitionFromRight; // 动画过渡方向
        anim.duration = 0.5; // 动画持续1s
        // 代理，动画执行完毕后会调用delegate的animationDidStop:finished:
        anim.delegate = self;
        [self.picImageView.layer addAnimation:anim forKey:@"layer"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
